﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
using Top.Api.Util;
using Newtonsoft.Json.Linq;
using LeShiTao_Library.TB_Top;
using System.IO;

namespace TB_WS.WEB
{
	public partial class Authorize : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            string code = Request.QueryString["code"];
            Label1.Text = code;
            string url = "https://oauth.taobao.com/token";
            Dictionary<string, string> props = new Dictionary<string, string>();
            props.Add("grant_type", "authorization_code");
            props.Add("code", code);
            props.Add("client_id", "23595706");
            props.Add("client_secret", "2e01c32c2d5a7044b7cb58aa88f7d55e");
            props.Add("redirect_uri", "http://lstwechat.59igou.com/web/authorize.aspx");
            props.Add("view", "web");
            string s = "";

            try
            {
                WebUtils webUtils = new WebUtils();
                s = webUtils.DoPost(url, props);
                Class.QN.Top_Session CTS = new Class.QN.Top_Session(s.ToString());
                //taobao_user_nick 淘宝ID
                string taobao_user_nick = CTS.Get_taobao_user_nick().ToString();
                //Access_Token
                string Access_Token = CTS.Get_access_token().ToString();
                //expires_in 超时时间
                Int64 expires_in = Convert.ToInt64(CTS.Get_expires_in().ToString());
                if(Class.QianNiu.get_QN_Nick_Count(taobao_user_nick)==0)
                {
                    //没有NICK
                    Class.QianNiu.Insert_QN_Info(taobao_user_nick,
                        Access_Token, expires_in+LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP());
                }
                {
                    //有NICK 已过期需要更新
                    Class.QianNiu.Update_QN_Access_Token(taobao_user_nick,
                        Access_Token, expires_in + LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP());
                }
                //更新的问题解决后跳转新页面
                Response.Redirect("http://lstwechat.59igou.com/web/MainForm.aspx?Nick=" + taobao_user_nick);
            }
            catch (IOException ex)
            {
                Label1.Text = ex.Message.ToString();
                System.Diagnostics.Debug.Write(ex.Message.ToString());
            }
        }
    }
}